/**
 * Created by gaoyj on 2018/6/28.
 */
window.onload = function (ev) {
    topbar.hide();
};
var productIds = []
$("#addForm").validate({
    rules: {
        name: {
            required: true,
            minlength: 2
        },
        phoneNo: {
            required: true
        },
        loginPwd: {
            minlength: 6,
            maxlength: 20
        }
    }
});
$(function () {
    $.ajax({
        type: "POST",
        url: "/CardProductController/queryAllCardOperatorList",
        dataType: "json",
        success: function (data) {
            $("#productType").html("");
            var str1 = "<option value=\"\">全部</option>";
            var str = "";
            if (data != null && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    str += '<option value=' + data[i].cardOperatorId + '>' + data[i].cardOperatorName + '</option>'
                }
            }
            $("#productType").append(str1 + str);
            $("#productType1").append(str);
            $("#productType2").append(str);
            //缺一不可  
            $('.selectpicker').selectpicker('refresh');
            $('.selectpicker').selectpicker('render');
        },
        beforeSend: function () {
        }
    });
})
$('#dataTable').bootstrapTable({
    url: '/channel/list',
    height: $(window).height() - 200,
    pageSize: 30,
    pagination: true,
    pageList: [30, 50, 100],
    clickToSelect: true,
    queryParams: queryParams,
    uniqueId: 'id',
    queryParamsType: '',
    sidePagination: 'server',
    responseHandler: function (res) {
        return {
            "total": res.total,
            "rows": res.resultList
        };
    },
    columns: [
        {
            checkbox: true
        },
        {
            align: 'center',
            formatter: function (v, row, index) {
                return index + 1
            }
        }, {
            align: 'center',
            field: 'cardProductId',
            title: '产品编号'
        }, {
            align: 'center',
            field: 'productName',
            title: '产品名称'
        },
        {
            align: 'center',
            field: 'face',
            title: '面值'
        }, {
            align: 'center',
            field: 'cardOperatorName',
            title: '运营商'
        }, {
            align: 'center',
            field: 'area',
            title: '地区'
        }, {
            align: 'center',
            field: 'state',
            title: '状态',
            formatter: function (v, row, index) {
                return productStatusFun[v];
            }
        }, {
            align: 'center',
            field: 'submitType',
            title: '上传方式',
            formatter: function (v, row, index) {
                return submitTypeFun[v];
            }
        }, {
            align: 'center',
            field: 'cardRestrict',
            title: '卡号卡密校验规则'
        },
        {
            align: 'center',
            field: 'modified',
            title: '修改时间',
            formatter: function (v, row, index) {
                var modifyTime = v == null ? "-" : changeDateFormat(v)
                return modifyTime;
            }
        }, {
            align: 'center',
            field: 'admin',
            title: '操作人'
        }, {
            align: 'center',
            field: 'remark',
            width: '100px',
            title: '备注'
        }
    ],
});

$("#search").click(function () {
    $("#dataTable").bootstrapTable("refresh");
});
$("#updateCardRestrict").click(function () {
    $("#cardRestrictModalForm").form("clear");
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的产品");
        return;
    }
    $("#updateCardRestrictModal").modal("show");
});
$("#updateCardRestrictBtn").click(function () {
    var cardRestrict = $("#editCardRestrict").val();
    if (cardRestrict == "" || cardRestrict == null) {
        layer.msg("请输入新的校验规则!");
        return;
    }
    productIds = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    for (var i = 0; i < rows.length; i++) {
        productIds.push(rows[i].id);
    }
    var productStr = productIds.join(",");
    $.confirm({
        title: '确认!',
        content: '确定要更新校验规则吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/product/updateCardRestrict",
                data: {
                    productIds: productStr,
                    cardRestrict: cardRestrict
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#updateCardRestrictModal").modal("hide");
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg("操作成功");
                    } else {
                        layer.msg(data.message)
                    }
                },
            });
        }
    });
});
$("#deleteProduct").click(function () {
    productIds = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    for (var i = 0; i < rows.length; i++) {
        productIds.push(rows[i].id);
    }
    var productStr = productIds.join(",");
    $.confirm({
        title: '确认!',
        content: '确定要删除这些产品吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/product/deleteProduct",
                data: {
                    productIds: productStr,
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg(data.message)
                    } else {
                        layer.msg(data.message)
                    }
                },
            });
        }
    });
});
//闲鱼状态触发事件
$("#actionType").change(function () {
    var actionType = $("#actionType").val();
    var spuHidden = $("#spuId_hidden").val();
    if (actionType == 1 || spuHidden != '') {
        $("#spuId").attr("readonly", true);
    } else {
        $("#spuId").attr("readonly", false);
    }
    $("#spuId").val(spuHidden);
});

function updateStatus(v) {
    productIds = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的产品");
        return;
    }
    for (var i = 0; i < rows.length; i++) {
        productIds.push(rows[i].id);
    }
    var productStr = productIds.join(",");

    var title = "";
    if (v == 1) {
        title = "上架"
    } else if (v == 0) {
        title = "下架"
    } else if (v == 2) {
        title = "维护"
    }
    $("#productStr").val(productStr);
    $("#handleState").val(title);
    $("#handleStateCode").val(v);
    $("#remark").val("");
    $("#myModal1").modal("show");
}

//备注保存
$("#toSaveRemark").click(function () {
    var remark = $('#remark').val();
    if (remark == null || remark == "") {
        layer.msg("备注不能为空!");
        return;
    }
    if (remark.length > 250) {
        layer.msg("输入备注超长!");
        return;
    }
    var productStr = $('#productStr').val();
    $.confirm({
        title: '确认!',
        content: '确定要' + $("#handleState").val() + '吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/product/changeProductStatus",
                data: {
                    productIds: productStr,
                    status: $("#handleStateCode").val(),
                    remark: $("#remark").val()
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg("操作成功");
                        $("#myModal1").modal("hide");
                    } else {
                        layer.msg(data.message)
                    }
                },
            });
        }
    });
});
//新增弹窗
$("#add").click(function () {
    $("#addProductForm").form('clear');
    ;
    $("#addProductLabel").text("新增产品信息");
    $("input[name=JSESSIONID]").val(sessionStorage.getItem('JSESSIONID'));
    $("#addProduct").modal({backdrop: 'static', keyboard: false});
});
//修改弹窗
$("#editProduct").click(function () {
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的产品");
        return;
    }
    if (rows.length > 1) {
        layer.msg("请选择1条操作记录");
        return;
    }

    $("#edit_id").val(rows[0].id);
    $("#productName2").val(rows[0].productName);
    $("#cardProductId2").val(rows[0].cardProductId);
    //默认选中
    $('#productType2_div .selectpicker').selectpicker('val', rows[0].productType);
    $('#productType2_div .selectpicker').selectpicker('refresh');
    $("#area2").val(rows[0].area);

    $("#face2").val(rows[0].face);
    $("#state2").val(rows[0].state);
    $("#submitType2").val(rows[0].submitType);
    $("#cardRestrict2").val(rows[0].cardRestrict);
    $("#editProductModal").modal("show");
});
//新增产品提交
$("#addProductSubmit").click(function () {
    var v = $("#addProductForm").valid();
    if (!v) {
        return;
    }
    $.ajax({
        type: "post",
        url: "product/addProduct",
        data: $("#addProductForm").serialize(),
        dataType: "json",
        async: false,
        cache: false,
        success: function (data) {
            if (data.success) {
                $("#dataTable").bootstrapTable("refresh");
                $("#addProduct").modal("hide");
                layer.msg('操作成功');
            } else {
                layer.msg(data.message)
            }
        }
    });
})
//修改产品提交
$("#editProductSubmit").click(function () {
    var v = $("#editProductForm").valid();
    if (!v) {
        return;
    }
    $.ajax({
        type: "post",
        url: "product/editProduct",
        data: $("#editProductForm").serialize(),
        dataType: "json",
        async: false,
        cache: false,
        success: function (data) {
            if (data.success) {
                $("#dataTable").bootstrapTable("refresh");
                $("#editProductModal").modal("hide");
                layer.msg('操作成功');
            } else {
                layer.msg(data.message)
            }
        }
    });
})
//spu保存
$("#saveSpu").click(function () {
    var rows = $('#dataTable').bootstrapTable("getSelections");
    var actionType = $("#actionType").val();
    if (actionType == '') {
        layer.msg("请选择闲鱼状态!");
        return;
    }
    if (actionType == 0 && $("#spuId").val() == '') {
        layer.msg("请输入闲鱼SPU!");
        return;
    }
    if ($("#spuId_hidden").val() == '' && actionType == 1) {
        layer.msg("未挂载spu!");
        return;
    }
    if ($("#spuId").val().length > 10) {
        layer.msg("spu编码超长(长度<=10)!");
        return;
    }
    $.confirm({
        title: '确认!',
        content: '确定要对闲鱼端：' + rows[0].productName + '【<span style=\'color:red;font-weight:bold;\'>' + {
            "0": "上架",
            "1": "下架"
        }[actionType] + '</span>】吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: '/product/xianyuTicketSpuModify',
                data: {
                    actionType: actionType,
                    cardProductId: $("#cardProductId_SPU").val(),
                    spuId: $("#spuId").val(),
                    productType: $("#productType_SPU").val()
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#myModalBySpu").modal("hide");
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg("操作成功");
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        }
    })

});
//闲鱼状态触发事件
$("#actionType").change(function () {
    var actionType = $("#actionType").val();
    var spuHidden = $("#spuId_hidden").val();
    if (actionType == 1 || spuHidden != '') {
        $("#spuId").attr("readonly", true);
    } else {
        $("#spuId").attr("readonly", false);
    }
    $("#spuId").val(spuHidden);
});

function queryParams(params) {
    return {
        'pageUnit.size': params.pageSize,
        'pageUnit.page': params.pageNumber,
        productName: $.trim($("#productName").val()),
        face: $.trim($("#face").val()),
        area: $("#area").val(),
        productType: $("#productType").val(),
        state: $("#state").val(),
        cardProductId: $("#productNo").val(),
        ticketSpuid: $("#ticketSpuid_query").val(),
        spuStatus: $("#spuStatus").val()
    };
}

//闲鱼spu上下架
function updateXianyuSpuStatus() {
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length == 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    //操作限制
    var cardProductIdArr = [];
    for (var i = 0; i < rows.length; i++) {
        if (i > 0) {
            if (rows[i - 1].productType != rows[i].productType) {
                layer.msg("请选择相同'运营商'进行操作");
                return;
            }
            if (rows[i - 1].submitType != rows[i].submitType) {
                layer.msg("请选择相同'上传方式'进行操作");
                return;
            }
        }
        cardProductIdArr.push(rows[i].cardProductId);
    }

    $("#spuId_hidden").val(rows[0].ticketSpuid);
    $("#actionType").val("");
    $("#ticketSpuid").val("");
    $("#spuId").val("");
    $("#cardProductId_SPU").val(cardProductIdArr);
    $("#productType_SPU").val(rows[0].productType);
    $("#myModalBySpu").modal("show");
}